package crypt;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import java.security.spec.DSAParameterSpec;
/**
 * Class that handles creation of keys
 * 
 * @author jonas.lindmark
 */
public class KeyHandler {
    /**
     * Create a new key pair
     * 
     * @param priv_file file to write private file to
     * @param pub_file  file tor write public file to
     */
    public void genKeys(String priv_file,String pub_file){
        try {
            AlgorithmParameterGenerator dsapg = AlgorithmParameterGenerator.getInstance("DSA");
            dsapg.init(1024);
            AlgorithmParameters param = dsapg.generateParameters();
            DSAParameterSpec param_spec = (DSAParameterSpec)param.getParameterSpec(DSAParameterSpec.class);

            KeyPairGenerator key_gen = KeyPairGenerator.getInstance("DSA");
            key_gen.initialize(param_spec);

            KeyPair keys = key_gen.genKeyPair();
            
            printObject(keys.getPrivate(),priv_file);
            printObject(keys.getPublic(),pub_file);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    //utility function for writing any object to a file
    private void printObject(Object o, String file) throws Exception {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
        out.writeObject(o);
        out.flush();
        out.close();
    }
}
